package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    @Transactional
    public R saveDish(@RequestBody DishDto dishDto) {
        //保存菜品数据到dish表
        dishService.save(dishDto);

        //保存口味数据到dish_flavors表
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置口味对应的菜品id
            flavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    //分页查询菜品
    @GetMapping("/page")
    public R pageGroup(Integer page, Integer pageSize, String name) {

        IPage<Dish> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        qw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageinfo, qw);

        //List<Dish>--->List<DishDto>
        List<Dish> records = pageinfo.getRecords();
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            //dish--->dishDto
            //寻找分类名称
            Long categoryId = dish.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);//根据id找内容
            String categoryName = category.getName();

            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtil.copyProperties(dish, dishDto);
            dishDtos.add(dishDto);
        }

        Integer total = Math.toIntExact(pageinfo.getTotal());

        Map map = new HashMap();
        map.put("records", dishDtos);
        map.put("total", total);

        return R.success(map);
    }

    //根据id查询菜品,用于回显
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        DishDto dishDto = new DishDto();

        Dish dish = dishService.getById(id);
        BeanUtil.copyProperties(dish, dishDto);

        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(qw);
        dishDto.setFlavors(flavors);

        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    @Transactional
    public R updatedish(@RequestBody DishDto dishDto) {
        dishService.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(qw);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("修改菜品成功");
    }

    //删除菜品
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids) {
        //1.删除菜品对应的口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(qw);

        //2.删除菜品
        dishService.removeByIds(ids);

        /*List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            Long categoryId = dish.getCategoryId();

            //清理某个分类下面的菜品缓存数据
            String key = "dish_" + categoryId + "_1";
            redisTemplate.delete(key);
        }*/
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("删除成功");

    }

    //修改菜品销售状态:起售,停售
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        /*LambdaUpdateWrapper<Dish> qw=new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus,status);
        qw.in(Dish::getId,ids);
        dishService.update(qw);*/

        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(status);
            //Long categoryId = dish.getCategoryId();

            /*//清理某个分类下面的菜品缓存数据
            String key = "dish_" + categoryId + "_"+status;
            redisTemplate.delete(key);*/

        }
        dishService.updateBatchById(dishes);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("操作成功");

    }


    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public R dishlist(Long categoryId, Integer status) {
        List<DishDto> dishDtos = null;
        String key = "dish_" + categoryId + "_" + status;
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos!=null){
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId != null, Dish::getCategoryId, categoryId);
        qw.eq(Dish::getStatus, status);
        List<Dish> list = dishService.list(qw);
        dishDtos = new ArrayList<>();

        for (Dish dish : list) {
            DishDto dishDto = new DishDto();

            BeanUtil.copyProperties(dish, dishDto);

            LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(qw1);
            dishDto.setFlavors(dishFlavors);

            dishDtos.add(dishDto);
        }

        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        return R.success(dishDtos);

    }

}
